package com.shanghaionstar.nav;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.sqlite.entities.RouteHistory;
import com.onstar.cn.map.common.PoiItemInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.adapter.PoiRouteHistoryListAdapter;
import com.shanghaionstar.nav.iview.INavRoutePlanView;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.SetAddressResult;
import com.shanghaionstar.nav.presenter.NavRoutePlanPresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.weight.TopLayout;

import java.util.List;

/**
 * @author jun chen
 * @ClassName: NavRoutePlanFragment
 * @date 2016年2月3日 下午3:45:32
 * @Description: 路线规划页面
 */
public class NavRoutePlanFragment extends BaseFragment implements INavRoutePlanView {
    private AbstractMapActivity mapActivity;

    //    @FindViewById(R.id.path_plan_headview)
//    private HeadViewLayout mHeadView;
    @FindViewById(R.id.route_start_edit_id)
    private TextView mStartTv;
    @FindViewById(R.id.route_end_edit_id)
    private TextView mEndTv;
    @FindViewById(R.id.route_plan_listview)
    private ListView mPlanLv;
    @FindViewById(R.id.poi_clear_histroy_view)
    private RelativeLayout mClearRl;
    @FindViewById(R.id.text_route_history)
    private TextView mHisRouteTv;

    private PoiRouteHistoryListAdapter mHisAdapter;
    private NavRoutePlanPresenter mRoutePresenter;

    @FindViewById
    private TopLayout top_layout;
    private PoiItemInfo currentMapChoosePoi;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mapActivity = (AbstractMapActivity) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isFirstLoad()) {
            mRoutePresenter = new NavRoutePlanPresenter(mapActivity.getScheduler(), mapActivity);
            initView();
            mRoutePresenter.setView(this);
            currentMapChoosePoi = mapActivity.getNavDataHolder().getCurrentMapPoi();
            top_layout.setRightBtnRes(R.drawable.nav_search);
            mRoutePresenter.setStartPoi(currentMapChoosePoi);
            mRoutePresenter.initData();
            top_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Routeplanning_return.getStringValue());
                    goBack();
                }
            });
        }
    }


    private Dialog commonDialog;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            if (mapActivity.getNavDataHolder().getStartPoi() != null) {
//                mStartTv.setText(mapActivity.getNavDataHolder().getStartPoi().getTitle());
//                mRoutePresenter.setStartPoi(mapActivity.getNavDataHolder().getStartPoi());
//            }
//            if (mapActivity.getNavDataHolder().getEndPoi() != null) {
//                mEndTv.setText(mapActivity.getNavDataHolder().getEndPoi().getTitle());
//                mRoutePresenter.setEndPoi(mapActivity.getNavDataHolder().getEndPoi());
//            }
//            mapActivity.clearMapRoutePoi();
//            mRoutePresenter.getRouteHistory();
        }
    }


    public void showDialog(final TextView routeHisTv, final RelativeLayout clearView) {
        AlertDialog.Builder b = new AlertDialog.Builder(mapActivity);
        b.setMessage("是否清除路线规划历史");
        b.setNegativeButton(R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mRoutePresenter.clear();
                mHisAdapter.notifyDataSetChanged();
                clearView.setVisibility(View.GONE);
                routeHisTv.setVisibility(View.GONE);
            }
        });
        b.setPositiveButton(R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        commonDialog = b.create();
        commonDialog.setCancelable(true);
        commonDialog.show();
    }

    private void initView() {
//        mHeadView.setLeftBtnOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                BusinessUtil.sendReportByClickType(mapActivity,
//                        FunctionNameFindId.Routeplanning_return.getStringValue());
//                back();
//            }
//        });

        top_layout.setOnRightClickListener("", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String routeStart = mStartTv.getText().toString().trim();
                String routeEnd = mEndTv.getText().toString().trim();
                mRoutePresenter.rightSearch(routeStart, routeEnd);
            }
        });
//        mHeadView.setRbtnOnClickListener(R.drawable.nav_right_search, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String routeStart = mStartTv.getText().toString().trim();
//                String routeEnd = mEndTv.getText().toString().trim();
//                mRoutePresenter.rightSearch(routeStart, routeEnd);
//            }
//        });
        mPlanLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mRoutePresenter.onItemClick(position);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        //获取本地的路线规划历史记录
        mRoutePresenter.getRouteHistory();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        mHeadView = null;
        mRoutePresenter.onDestroy();
    }


    @Override
    public int getLayoutId() {
        return R.layout.nav_route_planning;
    }

    @OnClick({R.id.route_switch_button_id, // 切换开始和终止位置
            R.id.route_start_edit_id, R.id.route_end_edit_id, R.id.poi_clear_histroy_view})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.route_switch_button_id:
                mRoutePresenter.switchClick();
                break;
            case R.id.route_start_edit_id:// 起点位置信息
                mRoutePresenter.startClick();
                break;
            case R.id.route_end_edit_id:// 终点位置信息 BusinessUtil.sendReportByClickType(mapActivity,
                mRoutePresenter.endClick();
                break;
            case R.id.poi_clear_histroy_view://清除路线规划的搜索历史
                showDialog(mHisRouteTv, mClearRl);
                break;
        }
    }


    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    public Activity onActivity() {
        return mapActivity;
    }

    @Override
    public void setText(String startTitle, String endTitle) {
        mStartTv.setText(startTitle == null ? "" : startTitle);
        mEndTv.setText(endTitle == null ? "" : endTitle);
    }

    @Override
    public void refreshView(List<RouteHistory> routeHistoryList) {
//        mHisRouteTv, mClearRl, mPlanLv
        if (routeHistoryList != null && routeHistoryList.size() > 0) {
            mHisRouteTv.setVisibility(View.VISIBLE);
            mClearRl.setVisibility(View.VISIBLE);
//            int length = Integer.valueOf(BusinessUtil.getConfigValue(FinalConfigParams.POILENGTH, mapActivity));
            int length = Constants.POILENGTH;
            mHisAdapter = new PoiRouteHistoryListAdapter(routeHistoryList, mapActivity, length);
            mPlanLv.setAdapter(mHisAdapter);
        } else {
            mHisRouteTv.setVisibility(View.GONE);
            mClearRl.setVisibility(View.GONE);
        }
    }

    @Override
    public void switchTxt() {
        String routeStartText = mStartTv.getText().toString().trim();
        String routeEndText = mEndTv.getText().toString().trim();
        mStartTv.setText(routeEndText);
        mEndTv.setText(routeStartText);
        mRoutePresenter.switchStartEndPoi();
    }

    public static NavRoutePlanFragment newInstance(PoiItemInfo currentMapPoi) {
        NavRoutePlanFragment navRoutePlanFragment = new NavRoutePlanFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("startPoi", currentMapPoi);
        navRoutePlanFragment.setArguments(bundle);
        return navRoutePlanFragment;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            Object obj = data.getSerializableExtra("result");
            if (obj instanceof SetAddressResult) {
                SetAddressResult setAddressResult = (SetAddressResult) obj;
                if (setAddressResult.mapChoosePoiType == MapChoosePoiType.START_POI) {
                    mStartTv.setText(setAddressResult.poiItemInfo.getTitle());
                    mRoutePresenter.setStartPoi(setAddressResult.poiItemInfo);
                }
                if (setAddressResult.mapChoosePoiType == MapChoosePoiType.END_POI) {
                    mEndTv.setText(setAddressResult.poiItemInfo.getTitle());
                    mRoutePresenter.setEndPoi(setAddressResult.poiItemInfo);
                }
                mRoutePresenter.getRouteHistory();
            }
        }

    }
}
